$(document).ready(function () {
    initPageFunction();
    $("#left").empty();
    session_check();
});

function initPageFunction () {
    var rpcmethods = ["getTimeOut", "getUserAgent", "setPassword", "setTimeOut", "setUserAgent", "setUsername", "getPublicTimeline", "getFriendsTimeline", "getUserTimeline", "getMentionsReplies", "getStatus", "updateStatus", "deleteStatus", "getUser", "getFriends", "getFollowers", "getDirectMessages", "getSentDirectMessages", "sendDirectMessage", "deleteDirectMessage", "createFriendship", "deleteFriendship", "existsFriendship", "getFriendship", "getFriendIds", "getFollowerIds", "verifyCrendentials", "getRateLimitStatus", "endSession", "updateDeliveryDevice", "updateProfileColors", "updateProfileImage", "updateProfileBackgroundImage", "updateProfile", "getFavorites", "createFavorite", "deleteFavorite", "follow", "unfollow", "createBlock", "deleteBlock", "existsBlock", "getBlocked", "getBlockedIds", "test", "isUserSet", "setUserCookie", "getMyUserName"];

    ptrpc = new PHPRPC_Client('php/peetweet_rpc.php', rpcmethods);  

    ptrpc.setKeyLength(128);
    ptrpc.setEncryptMode(2);

    urlReg = /((http|https|ftp)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}([a-zA-Z0-9]*)?\/?([a-zA-Z0-9\-\._\?\,\'\/\\\+%\$#\=~])*[^\.\,\)\(\s])/;
    atReg = /(@(([\w\_\.\-])+))/g;

    myUserName = "";

    $("#nav_logoff").click (function () {
            $.cookie ("pt_usr", null);
            $.cookie ("pt_psw", null);
            ptrpc.endSession(function () {
                location.reload(true);
            });
            return false;
    });
    $("#login_btn").click (function (){
            onLoginBtnClicked();
            return false;
    });
    $("#submit_btn").click (function () {
            onUpdateButtonClick();
            return false;
    });
    $("#getOlderStatus").click (function () {
            showOlderFriendsStatus();
            return false;
            });
    $("#new_results_notification").click(function(){
        $("#new_results_notification").slideUp("slow");
        $("#allTimeline .buffered_tweet").removeClass("buffered_tweet");
        $("#tweet_count").text('0');
        return false;
        });

    $("#menu_home").click(function (){
        if (!$("#allTimeline").hasClass("timeline_visible")) {
            $("#statuses ol.timeline_visible").removeClass("timeline_visible");
            $("#allTimeline").addClass("timeline_visible");
        }
        showNewerFriendsStatus();
        return false;
        });

    $("#menu_at").click (function () {
        if (!$("#atTimeline").hasClass("timeline_visible")) {
            $("#statuses ol.timeline_visible").removeClass("timeline_visible");
            $("#atTimeline").addClass("timeline_visible");
        }
        showNewerMentionedStatus();
        return false;
        });
}

function session_check() {
    ptrpc.isUserSet(function (r) {
            if (r) {
                var ajax_circle = $("<center />").append($('<img src="img/ajax.gif">')).appendTo("#left");
                ptrpc.verifyCrendentials(function (r) {
                    $(ajax_circle).remove();
                    if (r) 
                        onFirstLogin();
                    else 
                        showLoginScreen("Authentication Error. :(");
                });
            }
            else
                showLoginScreen();
    });
}

function showLoginScreen (error_msg) {
        $("#login_sec").appendTo("#left");
        if (error_msg)
            showLoginError(error_msg);
}

function showLoginError(error_msg) {
    $('<span class="error_banner" />').text(error_msg).prependTo("#login_sec").slideDown('fast', function (){
            $(this).oneTime(3000, function (){
                $(this).slideUp('slow', function (){
                    $(this).remove();
                    });
                });
            });
}

function onLoginBtnClicked () {
    var u = $("#login_usr").attr("value");
    var p = $("#login_psw").attr("value");
    if (! (u && p)) {
        showLoginError("You forgot to fill your account   :)");
        return false;
    }
    loginUser(u, p);
}

function loginUser(usr, psw) {
    if (! (usr && psw))
        return false;
    var ajax_circle = $("<center />").append($('<img src="img/ajax.gif">')).appendTo("#left");
    ptrpc.setUsername(usr, function () {
            ptrpc.setPassword(psw, function () {
                ptrpc.verifyCrendentials(function (r) {
                    $(ajax_circle).remove();
                    if (r) {
                        if ($("#remember_me").attr("checked")) {
                            ptrpc.setUserCookie();
                        }
                        onFirstLogin();
                    }
                    else
                        showLoginError("Authentication Error. :( ");
                });
            });
    });
}

function onFirstLogin () {
    $("#login_sec").appendTo("#buffer_area");
    ptrpc.getMyUserName(function (r){
            myUserName = r;
            $("#menu_at > a").text("@" + r);
            $("#content_wrapper").appendTo("#left");
            showNewerFriendsStatus();
            showSideProfile();
            $("body").everyTime("60s", "TimeLineAutoRefresh", showNewerFriendsStatus);
    });
}

function buildStatus (status_obj) {
    var status_li = $("<li />").attr("id", status_obj.id);
    var status_auth = $('<span class="status_author" />').appendTo(status_li);
    var status_body = $('<span class="status_body" />').appendTo(status_li);
    var status_word = $('<span class="status_word" />').appendTo(status_body);
    var status_actions = $('<span class="status_actions" />').appendTo(status_li);
    var status_info = $('<span class="status_info" />').appendTo(status_li);
    var status_date = $('<span class="status_date">').appendTo(status_info);
    var status_src = $('<span class="status_source" />').appendTo(status_info);

    var user_info = $('<div class="user_info" />').appendTo(status_li);
    $("<p />").append("<b>Name: </b>").append(status_obj.user.name).appendTo(user_info);
    $("<p />").append("<b>Location: </b>").append(status_obj.user.location).appendTo(user_info);
    $("<p />").append("<b>Follower: </b>").append(status_obj.user.followers_count).appendTo(user_info);
    $("<p />").append("<b>Proteceted: </b>").append((status_obj.user.protected ? "Yes":"No" )).appendTo(user_info);
    $("<p />").append('<b>URL: </b>').append($('<a target="_blank" />').attr("href", status_obj.user.url).text(status_obj.user.url)).appendTo(user_info);
    $("<p />").append("<b>Bio: </b>").append(status_obj.user.description).appendTo(user_info);

    $('<a href="#" />').append($('<img />').attr('src', status_obj.user.profile_image_url).attr("alt", status_obj.user.name)).appendTo(status_auth).click (function () {
            $(user_info).slideToggle("slow");
            return false;
            });
    
    $(status_src).html("from " + status_obj.source);
    $(status_date).attr("title", status_obj.created_at).text(formatDate(status_obj.created_at));

    $('<a class="user_name" />').attr("href", '#').text(status_obj.user.screen_name).appendTo(status_word).click (function () {
            $(user_info).slideToggle("slow");
            return false;
    });

    var status_text = $('<span />').html(status_obj.text.replace(urlReg, '<a href="$1" rev="OutLink" target="_blank">$1</a>').replace(atReg, '<a href="#" rev="ScreenName">$1</a>'));
    processStatusText(status_text, status_li);
    $(status_word).append(status_text);

    if (status_obj.in_reply_to_status_id) {
        var status_reply = $('<span class="in_reply_to" />"').appendTo(status_info);
        var in_reply_name = /^@(([\w\_\.\-])+)/.exec(status_obj.text)[1];
        var reply_msg = $('<a href="#" />').text("in reply to " + in_reply_name).click(function (){
                var ajax_circle = $('<img src="img/ajax.gif">').appendTo(status_reply);
                ptrpc.getStatus(status_obj.in_reply_to_status_id, function (r){
                    $(ajax_circle).remove();
                    $(reply_msg).replaceWith($(reply_msg).text());
                    showQuickReply(r, status_info);
                });
                return false;
            });
            $(status_reply).append(reply_msg);
    }
    var btn_rt = $('<a href="#">RT</a>').click(function () {
            $("#in_reply_to").attr("value","");
            $("#textbox").attr("value","RT @" + status_obj.user.screen_name + ": " + status_obj.text);
            window.scrollTo(0,0);
            return false;
            }).hover(function (){
                $(this).find(":only-child").removeClass("rt_btn").addClass("rt_btn-hover")},
                function () {
                $(this).find(":only-child").removeClass("rt_btn-hover").addClass("rt_btn")}).append('<span class="btn_icon rt_btn" />');
    $('<span class="retweet btn_fadding" />').append(btn_rt).appendTo(status_actions);

    var btn_reply = $('<a href="#">Reply</a>').click(function () {
            $("#in_reply_to").attr("value", status_obj.id);
            $("#textbox").attr("value", "@" + status_obj.user.screen_name + " ");
            window.scrollTo(0,0);
            return false;
            }).hover(function (){
                $(this).find(":only-child").removeClass("reply_btn").addClass("reply_btn-hover");},
                function (){
                $(this).find(":only-child").removeClass("reply_btn-hover").addClass("reply_btn");}).append('<span class="btn_icon reply_btn" />');
    $('<span class="reply btn_fadding" />').append(btn_reply).appendTo(status_actions);

    if (status_obj.user.screen_name == myUserName) {
        var btn_del = $('<a href="#">Del</a>').click(function (){
                deleteTweet(status_obj.id, status_li);
                return false;
                }).hover(function(){
                    $(this).find(":only-child").removeClass("delete_btn").addClass("delete_btn-hover");},
                function (){
                    $(this).find(":only-child").removeClass("delete_btn-hover").addClass("delete_btn");}).append('<span class="btn_icon delete_btn" />');
        $('<span class="del btn_fadding" />').append(btn_del).appendTo(status_actions);
    }
    var btn_fav = $('<span class="favor" />').appendTo(status_li);
    var btn_fav_a = $('<a href="#" />');
    var fav_span = $('<span class="btn_icon" />').appendTo(btn_fav_a);
    if (status_obj.favorited)
        $(fav_span).addClass("favor_btn_faved");
    else {
        $(fav_span).addClass("favor_btn");
        $(btn_fav).addClass("btn_fadding");
    }

    $(btn_fav_a).click(function (){
            favoriteTweet(status_obj.id, $(this).find(":only-child")); 
            return false;
            }).appendTo(btn_fav);

    $(status_li).hover(
            function (){$(this).find(".btn_fadding").fadeIn("fast");},
            function (){$(this).find(".btn_fadding").fadeOut("fast");});

    return status_li;
}

function showSideProfile () {
    if (!myUserName) return;
    var side_info_div = $('<div id="sideinfo" />');
    var side_info_ul = $('<ul id="user_stats" />');

    var ajax_circle = $("<center />").append($('<img src="img/ajax.gif">')).prependTo("#side");

    ptrpc.getUser(myUserName, function (r) {
            $('<img id="sideimg" />').attr("src", r.profile_image_url).appendTo(side_info_div);
            $('<span id="sideid" />').text(r.screen_name).appendTo(side_info_div);
            $('<span id="sidename" />').text(r.name).appendTo(side_info_div);

            $("<li>").append($('<span class="count" />').text(r.friends_count)).append('<span class="label">Following</span>').appendTo(side_info_ul);
            $("<li>").append($('<span class="count" />').append($('<a href="#" />').text(r.followers_count))).append('<span class="label">Followers</span>').appendTo(side_info_ul);
            $("<li>").append($('<span class="count" />').text(r.statuses_count)).append('<span class="label">Tweets</span>').appendTo(side_info_ul);
            
            $(ajax_circle).remove();
            $(side_info_ul).prependTo("#side").slideDown();
            $(side_info_div).prependTo("#side").slideDown();
            });
}

function onUpdateButtonClick() {
    var text = $("#textbox").attr("value");
    var reply_to = $("#in_reply_to").attr("value");
    var ajax_circle = $("<center />").append($('<img src="img/ajax.gif">')).prependTo("#statuses_update_box");
    ptrpc.updateStatus(text, reply_to, function (r) {
        $(ajax_circle).remove();
        $("#allTimeline").prepend(buildStatus(r));
        $("#textbox").attr("value", "");
        $("#in_reply_to").attr("value", "");
    });
}

function updateStatusDate () {
    $(".status_date").each (function () {
        var time_val = $(this).attr("title");
        $(this).text(formatDate(time_val));
    });
}

function showQuickReply (status_obj, status_info) {
    if (!status_obj.text)
        return;
    var status_reply = $('<p display="none;" class="reply_msg" />').append($('<b />').text(status_obj.user.screen_name + ": ")).append($("<span />").html(status_obj.text.replace(urlReg, '<a href="$1" target="_blank">$1</a>')));
    $(status_info).after(status_reply);
    $(status_reply).slideDown('slow');
    if (status_obj.in_reply_to_status_id) {
        var reply_to = $('<a href="#">in reply to</a>').click(function () {
            var ajax_circle = $('<img src="img/ajax.gif">').appendTo(status_reply);
            ptrpc.getStatus(status_obj.in_reply_to_status_id, function (r) {
                showQuickReply(r, $(status_info).next());
                $(ajax_circle).remove();
                $(reply_to).remove();
            });
            return false;
        });
        $(status_reply).append(reply_to);
    }
}        

function processStatusText (status_text, status_li) {
    $(status_text).children("a").each (function () {
        if ($(this).attr("rev") == 'ScreenName'){
            //show user
        }
        else if($(this).attr("rev") == 'OutLink'){
            //if image, do something
            checkImageURL(this, status_li); 
        }
    });
}

function showNewerFriendsStatus() {
    var sinceID = $("#allTimeline > :first-child").attr("id");
    var ajax_circle = $("<center />").append($('<img src="img/ajax.gif">')).prependTo("#allTimeline");
    ptrpc.getFriendsTimeline(sinceID, function (r) {
            $(ajax_circle).remove();
            var tmp_line = $("<ul>");
            $(r).each (function () {
                $(tmp_line).append(buildStatus(this));
            });
            if ($("#allTimeline > *").size() > 0) {
                $(tmp_line).children().addClass("buffered_tweet");
                var org_count = parseInt($("#tweet_count").text());
                var new_count = $(tmp_line).children().size();
                if (new_count == 0)
                    return;
                $("#tweet_count").text(org_count + new_count);
                if ($("#new_results_notification").css("display") == 'none')
                    $("#new_results_notification").slideDown("slow");
            }
            $(tmp_line).children().prependTo("#allTimeline");
            updateStatusDate();
    });
}

function showOlderFriendsStatus() {
    var maxID = $("#allTimeline > :last-child").attr("id") - 1;
    $("<hr />").appendTo("#allTimeline");
    var ajax_circle = $("<center />").append($('<img src="img/ajax.gif">')).appendTo("#allTimeline");
    ptrpc.getFriendsTimeline(null, maxID, "20", function (r) {
            $(ajax_circle).remove();
            $(r).each (function () {
                $("#allTimeline").append(buildStatus(this));
            });
            updateStatusDate();
    });
}

function formatDate(unix_second) {
    var differ = parseInt((new Date()).getTime()/1000) - unix_second;
    if (differ < 60) {
        dateFormated = "less than " + differ + " seconds ago";
    } else if (differ < 3600) {
        dateFormated = parseInt(differ / 60) + " minutes ago";
    } else if (differ < 3600 * 24) {
        dateFormated = "about " + parseInt(differ / 3600) + " hours ago";
    } else {
        var d = new Date(unix_second * 1000);
        dateFormated = "at " + d.getFullYear() + "-" + d.getMonth() + "-" + d.getDate() + " " + (d.getHours() > 9 ? d.getHours():"0"+d.getHours()) + ":" + (d.getMinutes()  > 9 ? d.getMinutes() :"0"+d.getMinutes())+ ":" + (d.getSeconds() > 9 ? d.getSeconds() : "0" + d.getSeconds());
    }
    return dateFormated;
}

function deleteTweet(id, container) {
    if (!confirm("You sure to delete this tweet ?"))
        return;
    var ajax_circle = $('<img src="img/ajax.gif">').appendTo(container);
    ptrpc.deleteStatus(id, function () {
            $(ajax_circle).remove();
            $(container).fadeOut("slow");
            });
}

function favoriteTweet(id, starBtn) {
    var ajax_circle = $('<img src="img/ajax.gif">').appendTo(starBtn);
    var btn = $(starBtn).parent().parent();
    if ($(starBtn).hasClass("favor_btn_faved")) {
        ptrpc.deleteFavorite(id, function (){
                $(starBtn).removeClass("favor_btn_faved").addClass("favor_btn");
                $(btn).addClass("btn_fadding").fadeOut();
                $(ajax_circle).remove();
                });
    }
    else{
        ptrpc.createFavorite(id, function (){
                $(starBtn).removeClass("favor_btn").addClass("favor_btn_faved");
                $(btn).removeClass("btn_fadding").fadeIn();
                $(ajax_circle).remove();
                });
    }
}

function showNewerMentionedStatus() {
    var sinceID = $("#atTimeline > :first-child").attr("id");
    var ajax_circle = $("<center />").append($('<img src="img/ajax.gif">')).prependTo("#atTimeline");
    ptrpc.getMentionsReplies(sinceID, function (r) {
            $(ajax_circle).remove();
            var tmp_line = $("<ul>");
            $(r).each (function () {
                $(tmp_line).append(buildStatus(this));
            });
            /*
            if ($("#allTimeline > *").size() > 0) {
                $(tmp_line).children().addClass("buffered_tweet");
                var org_count = parseInt($("#tweet_count").text());
                var new_count = $(tmp_line).children().size();
                if (new_count == 0)
                    return;
                $("#tweet_count").text(org_count + new_count);
                if ($("#new_results_notification").css("display") == 'none')
                    $("#new_results_notification").slideDown("slow");
            } */
            $(tmp_line).children().prependTo("#atTimeline");
            updateStatusDate();
    });
}

